package org.starapp.plugins.shiro;

import java.text.MessageFormat;
import java.util.Iterator;
import java.util.List;

import org.apache.shiro.config.Ini;
import org.apache.shiro.config.Ini.Section;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.starapp.rbac.entity.Objects;
import org.starapp.rbac.entity.Operations;
import org.starapp.rbac.entity.Permissons;
import org.starapp.rbac.service.ObjectsService;
import org.starapp.rbac.service.PermissonsService;
import org.starapp.rbac.service.UsersService;
import org.starapp.utils.StringUtils;

public class ChainDefinitionSectionMetaSource implements
		FactoryBean<Ini.Section> {

	private PermissonsService permissonsService;

	private String filterChainDefinitions;
	
	@Autowired
	public void setPermissonsService(PermissonsService permissonsService) {
		this.permissonsService = permissonsService;
	}

	/**
	 * 默认premission字符串
	 */
	public static final String PREMISSION_STRING = "perms[\"{0}\"]";

	public Section getObject() throws BeansException {

		// 获取所有Permissions
		List<Permissons> list = permissonsService.getAllPermissons();

		Ini ini = new Ini();
		// 加载默认的url
		ini.load(filterChainDefinitions);
		System.out.println("hhhhhhhhhhhhhhhhhhhh"+filterChainDefinitions);
		Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
		// 循环Resource的url,逐个添加到section中。section就是filterChainDefinitionMap,
		// 里面的键就是链接URL,值就是存在什么条件才能访问该链接
		for (Iterator<Permissons> it = list.iterator(); it.hasNext();) {
			Permissons permissons = it.next();
			// 如果不为空值添加到section中
			Objects o = permissons.getObjects();
			Operations op=permissons.getOperations();
			if(o!=null&&op!=null){
			if (StringUtils.isNotBlank(o.getObjectId())) {
				section.put(permissons.getObjects().getObjectId(), MessageFormat.format(
						PREMISSION_STRING, op.getOperationId()));
			}
			}
		}
		System.out.println("jjjjjjjjjjjjjjj"+section.toString());
		return section;
	}

	/**
	 * 通过filterChainDefinitions对默认的url过滤定义
	 * 
	 * @param filterChainDefinitions
	 *            默认的url过滤定义
	 */
	public void setFilterChainDefinitions(String filterChainDefinitions) {
		this.filterChainDefinitions = filterChainDefinitions;
	}

	public Class<?> getObjectType() {
		return this.getClass();
	}

	public boolean isSingleton() {
		return false;
	}

}
